import logging
import os

from celery import Celery

from backend.app.core.config import settings

# 配置基本日志
logging.basicConfig(
    level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

os.environ["HUGGINGFACE_HUB_CACHE"] = os.path.join(os.getcwd(), "fastembed_cache")
os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
os.environ["HF_DATASETS_OFFLINE"] = "1"
os.environ["TRANSFORMERS_OFFLINE"] = "1"

celery_app = Celery(
    "worker",
    broker=settings.CELERY_BROKER_URL,
    # broker="redis://localhost:6379/0"
    backend=settings.CELERY_RESULT_BACKEND,
    # backend="redis://localhost:6379/0"
    include=["app.tasks.tasks"]
)

celery_app.conf.update(
    result_expires=3600,  # 任务结果过期时间（秒）
)

celery_app.conf.task_routes = {"app.worker.celery_worker.*": "main-queue"}
celery_app.conf.update(task_track_started=True)

# 配置 celery日志
celery_app.conf.update(
    worker_hijack_root_logger=False,
    worker_log_format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    worker_task_log_format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)


# 在 Celery 中，任务确认是一种机制，用于告知消息队列（broker）任务是否已经成功处理。默认情况下，acks_late 为 False，这意味着 Celery 工作进程（worker）在接收到任务后会立即向消息队列确认该任务，即便任务还未实际执行。而当 acks_late=True 时，工作进程会在任务执行完成之后才向消息队列确认任务。
def test_celery(word: str) -> str:
    logging.info(f"Test task received: {word}")
    return f"test task return {word}"
